package com.starbaba.spread.service.impl;

import com.base.common.database.BaseDao;
import com.base.common.exception.AppException;
import com.base.common.log.LogService;
import com.base.common.util.ObjectUtils;
import com.google.gson.JsonObject;
import com.jumai.server.common.util.TestMode;
import com.starbaba.core.hibernate.DAOFactory;
import com.starbaba.core.hibernate.HibernateDAO;
import com.starbaba.core.service.CommonService;
import com.starbaba.core.service.CommonServiceSupport;
import com.starbaba.core.utils.BeanUtils;
import com.starbaba.core.web.page.PageResponse;
import com.starbaba.model.dictionary.Constant;
import com.starbaba.model.utils.HttpConnectionUtils;
import com.starbaba.spread.model.*;
import com.starbaba.spread.service.SpreadService;
import org.apache.commons.lang.StringUtils;
import org.apache.http.message.BasicNameValuePair;
import org.hibernate.Query;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Component
public class SpreadServiceImpl extends CommonServiceSupport implements SpreadService{

	/**
	 * 
	 */
	private static final long serialVersionUID = -5108922671733677590L;
	private  SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

	@Override
	public List<TableVO> getDataList(int iDisplayStart, int iDisplayLength,
			SpreadChannelModel model, PageResponse pageResponse , CommonService server) {
		StringBuffer sf = new StringBuffer();
		sf.append("from DataVO as data, ChannelVO as channel where data.channel=channel.id");
		String condition = bulidCondition(model,server);
		sf.append(condition);
		sf.append(" order by data.date desc");
		String hql = sf.toString();
		String countHql = "select count(*) " + hql;
		HibernateDAO dao = DAOFactory.getInstance().createHibernateDAO(DataVO.class);
		Query  query = dao.getSession().createQuery(hql);
		if(iDisplayLength != 0)
		{
			query.setFirstResult(iDisplayStart);
			query.setMaxResults(iDisplayLength);
		}
		addTimeParm(model,query);
		List<Object[]> list = query.list();
		List<TableVO> returnList = new ArrayList<TableVO>();
		TableVO itemVo;
		SimpleDateFormat dateformat=new SimpleDateFormat("yyyy-MM-dd");
		Map<Long ,TableVO> map = new HashMap<Long ,TableVO>();
		for(Object[] obj :list)
		{
			itemVo = new TableVO();
			DataVO vo = (DataVO) obj[0];
			ChannelVO channel = (ChannelVO) obj[1];
			
			itemVo.setCount(vo.getCount());	
			if (null != vo.getDate()) {
				String date = dateformat.format(vo.getDate());
				itemVo.setDate(date);
			}
			itemVo.setChannel(channel.getName());
			itemVo.setId(vo.getId());
			itemVo.setWznum(vo.getWznum());
			returnList.add(itemVo);
		}
		
		Query countQuery = dao.getSession().createQuery(countHql);
		addTimeParm(model,countQuery);
		Object obj = countQuery.uniqueResult();
		if(obj instanceof Long)
		{
			int count = ((Long)obj).intValue();
			
			pageResponse.setITotalRecords(count);
			pageResponse.setITotalDisplayRecords(count);
		}
		
		return returnList;
	}
	
	
	public List<ShortLinkTableVO> getShortLink(int iDisplayStart, int iDisplayLength,
			SpreadChannelModel model, PageResponse pageResponse , CommonService server) throws Exception {
		String condition = bulidShortLinkCondition(model,server);
		String sql = "select * from short_link where activity != '推送' " + condition + " order by id DESC limit " + iDisplayLength + " offset " + iDisplayStart;
		BaseDao dao = new BaseDao(Constant.POOL_LIFE);
		
		List<ShortLinkTableVO> returnList = new ArrayList<ShortLinkTableVO>();
//		List<Short_Link> list = dao.list(sql, Short_Link.class);
		List<ShortLinkAddisusedModel> list = dao.list(sql, ShortLinkAddisusedModel.class);
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		for (ShortLinkAddisusedModel tmp : list) {
			ShortLinkTableVO itemVo = new ShortLinkTableVO();
			itemVo.setId(tmp.getId());
			itemVo.setMemo(tmp.getMemo());
			if (TestMode.isTestMode()) {
				itemVo.setShort_link(Constant.COMMON_HOST + "/share_service/redirect?from=" + tmp.getShort_link());
			} else {
				itemVo.setShort_link("http://tcir.cn/" + tmp.getShort_link());
			}
			
			itemVo.setUrl(tmp.getUrl());
			itemVo.setCtime(dateFormat.format(tmp.getCtime()));
			itemVo.setUnit_price(tmp.getUnit_price());
			itemVo.setLink_type(tmp.getLink_type());
			itemVo.setActivity(tmp.getActivity());
			itemVo.setIsused_link(tmp.getIsused_link());
			itemVo.setEnvironment(tmp.getEnvironment());
			returnList.add(itemVo);
		}
		
		int count = dao.getInt("select count(*) from short_link where 1=1" + condition);

			
		pageResponse.setITotalRecords(count);
		pageResponse.setITotalDisplayRecords(count);
		
		return returnList;
	}
	@Override
	public void setNginxName(String name, String url) throws Exception {
		String userUrl = "http://xmiles.cn/stat_service/common";
//		String userUrl = "http://localhost:9080/stat_service/common";
		JsonObject requestjson = new JsonObject();
		JsonObject dataBean = new JsonObject();
		dataBean.addProperty("prd_id", url);
		dataBean.addProperty("prd_name", name);
		dataBean.addProperty("interface_id", 405);
		requestjson.add("databean", dataBean);
		ArrayList<BasicNameValuePair> pair = new ArrayList<BasicNameValuePair>();
		pair.add(new BasicNameValuePair("data", requestjson.toString()));
		pair.add(new BasicNameValuePair("shandle", "1"));
		pair.add(new BasicNameValuePair("handle", "0"));
		System.out.println("//////" + ObjectUtils.toJsonString(pair));
		String result = HttpConnectionUtils.connectionZip(userUrl, HttpConnectionUtils.POST, pair);
		LogService.info(result);
	}

	@Override
	public int update(ShortLinkAddisusedModel model) {
		BaseDao dao = new BaseDao(Constant.POOL_LIFE);
		if (!BeanUtils.checkFieldValueNull(model)){
			if (model.getIsused_link()==null||0==model.getIsused_link()){
				model.setIsused_link(1);
			}else{
				model.setIsused_link(0);
			}
		}
		int num = 0;
		try {
			num=dao.update("update short_link set isused_link=? where id=?",model.getIsused_link(),model.getId());
		} catch (AppException e) {
			e.printStackTrace();
		}
		return num;
	}


	@Override
	public ShortLinkAddisusedModel queryShortLinkAddisusedModel(String id) throws Exception {
		String sql = "select *from short_link where id="+id;
		ShortLinkAddisusedModel models = new ShortLinkAddisusedModel();
		BaseDao dao = new BaseDao(Constant.POOL_LIFE);
		List<ShortLinkAddisusedModel> list = dao.list(sql, ShortLinkAddisusedModel.class);
		if (list.size()>0)
			models = list.get(0);
		else
			throw new Exception("未查到任何数据");
		return models;
	}


	private void addTimeParm(SpreadChannelModel model, Query query) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
		String startTimeStr = model.getStartTime();
		String endTimeStr = model.getEndTime();
		try {
			if (!StringUtils.isEmpty(startTimeStr)) {
				query.setTimestamp("startime", format.parse(startTimeStr));
			}
			if (!StringUtils.isEmpty(endTimeStr)) {
				query.setTimestamp("endtime", format.parse(endTimeStr));
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}

	private String bulidCondition(SpreadChannelModel model, CommonService server) {
		StringBuffer condition = new StringBuffer();
		condition.append(" and status=1");
		String channel = model.getChannel();
		if (!StringUtils.isEmpty(channel)) {
			condition.append(" and name like '%" + channel + "%'");
		}
		
		Long type = model.getType();
		if (null != type) {
			condition.append(" and channel='" + type + "'");
		}
		
		String startTimeStr = model.getStartTime();
		if(!StringUtils.isEmpty(startTimeStr)) {
			condition.append(" and date > :startime");
		}
		
		String endTimeStr = model.getEndTime();
		if(!StringUtils.isEmpty(endTimeStr)) {
			condition.append(" and date <= :endtime");
		}
		return condition.toString();
	}
	
	private String bulidShortLinkCondition(SpreadChannelModel model, CommonService server) {
		StringBuffer condition = new StringBuffer();

		String memo = model.getMemo();
		String activity  = model.getActivity();
		String shortLink = model.getShortLink();
		if (!StringUtils.isEmpty(memo)) {
			condition.append(" and memo like '%" + memo + "%'");
		}
		if (!StringUtils.isEmpty(activity)) {
			condition.append(" and activity like '%" + activity + "%'");
		}

		if(StringUtils.isNotBlank(shortLink)){
			condition.append(" and short_link like '%" + shortLink + "%'");
		}

		return condition.toString();
	}
	
}
